//
//  buyOperation.m
//  alotOf
//
//  Created by Mac_Black_Mini on 2025/9/3.
//

#import "BuyOperation.h"

NS_ASSUME_NONNULL_BEGIN
@interface BuyOperation ()
#pragma mark - 私有属性

// 回调保存
@property (nonatomic, copy) IAPCompletion completion;
@end

@implementation BuyOperation
// 单例实现
+ (instancetype)sharedInstance {
    static BuyOperation *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[BuyOperation alloc] init];
        // 注册交易观察者
        [[SKPaymentQueue defaultQueue] addTransactionObserver:instance];
    });
    return instance;
}

- (instancetype)init {
    if (self = [super init]) {
        // 初始化操作
    }
    return self;
}

#pragma mark - 请求商品

- (void)requestProductsWithIds:(NSArray<NSString *> *)productIds completion:(IAPCompletion)completion {
    if (!productIds || productIds.count == 0) {
        if (completion) {
            NSError *error = [NSError errorWithDomain:@"IAPManager" code:-1 userInfo:@{NSLocalizedDescriptionKey:@"商品ID数组为空"}];
            completion(IAPStatusFailed, nil, error);
        }
        return;
    }
    
    // 保存回调
    self.completion = completion;
    
    // 创建商品请求
    NSSet *productIdentifiers = [NSSet setWithArray:productIds];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
    request.delegate = self;
    [request start];
}

#pragma mark - 购买商品

- (void)purchaseProduct:(SKProduct *)product completion:(IAPCompletion)completion {
    if (!product) {
        if (completion) {
            NSError *error = [NSError errorWithDomain:@"IAPManager" code:-2 userInfo:@{NSLocalizedDescriptionKey:@"商品对象为空"}];
            completion(IAPStatusFailed, nil, error);
        }
        return;
    }
    
    // 检查是否允许内购
    if (![SKPaymentQueue canMakePayments]) {
        if (completion) {
            NSError *error = [NSError errorWithDomain:@"IAPManager" code:-3 userInfo:@{NSLocalizedDescriptionKey:@"用户不允许内购"}];
            completion(IAPStatusFailed, nil, error);
        }
        return;
    }
    
    // 保存回调
    self.completion = completion;
    
    // 创建支付请求
    SKPayment *payment = [SKPayment paymentWithProduct:product];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

#pragma mark - 恢复购买

- (void)restorePurchasesWithCompletion:(IAPCompletion)completion {
    self.completion = completion;
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

#pragma mark - 验证凭证

- (void)verifyReceipt:(NSData *)receiptData isSandbox:(BOOL)isSandbox completion:(IAPCompletion)completion {
    if (!receiptData) {
        if (completion) {
            NSError *error = [NSError errorWithDomain:@"IAPManager" code:-4 userInfo:@{NSLocalizedDescriptionKey:@"凭证数据为空"}];
            completion(IAPStatusUnverified, nil, error);
        }
        return;
    }
    
    // 准备请求数据
    NSDictionary *requestDict = @{@"receipt-data": [receiptData base64EncodedStringWithOptions:0]};
    NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestDict options:0 error:nil];
    
    // 验证URL (正式环境/沙盒环境)
    NSString *verifyURLString = isSandbox ?
        @"https://sandbox.itunes.apple.com/verifyReceipt" :
        @"https://buy.itunes.apple.com/verifyReceipt";
    
    NSURL *url = [NSURL URLWithString:verifyURLString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = requestData;
    
    // 发送验证请求
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion(IAPStatusUnverified, nil, error);
                }
            });
            return;
        }
        
        if (data) {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
            if (error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (completion) {
                        completion(IAPStatusUnverified, nil, error);
                    }
                });
                return;
            }
            
            // 解析验证结果
            NSInteger status = [result[@"status"] integerValue];
            if (status == 0) {
                // 验证成功
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (completion) {
                        completion(IAPStatusVerified, result, nil);
                    }
                });
            } else if (status == 21007 && !isSandbox) {
                // 正式环境验证失败，尝试沙盒环境
                [self verifyReceipt:receiptData isSandbox:YES completion:completion];
            } else {
                // 验证失败
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (completion) {
                        NSError *verifyError = [NSError errorWithDomain:@"IAPManager" code:status userInfo:@{NSLocalizedDescriptionKey:[NSString stringWithFormat:@"验证失败，状态码：%ld", (long)status]}];
                        completion(IAPStatusUnverified, result, verifyError);
                    }
                });
            }
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    NSError *error = [NSError errorWithDomain:@"IAPManager" code:-5 userInfo:@{NSLocalizedDescriptionKey:@"验证返回数据为空"}];
                    completion(IAPStatusUnverified, nil, error);
                }
            });
        }
    }];
    [task resume];
}

#pragma mark - SKProductsRequestDelegate

// 商品请求完成
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    if (response.products.count > 0) {
        // 获取商品成功
        if (self.completion) {
            self.completion(IAPStatusSuccess, @{@"products": response.products}, nil);
        }
    } else {
        // 没有获取到商品
        if (self.completion) {
            self.completion(IAPStatusNoProducts, @{@"invalidIds": response.invalidProductIdentifiers}, nil);
        }
    }
    self.completion = nil;
}

// 商品请求失败
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
    if (self.completion) {
        self.completion(IAPStatusFailed, nil, error);
    }
    self.completion = nil;
}

#pragma mark - SKPaymentTransactionObserver

// 交易状态变化
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:
                // 购买中
                NSLog(@"购买中...");
                break;
                
            case SKPaymentTransactionStatePurchased:
                // 购买成功
                [self handlePurchasedTransaction:transaction];
                break;
                
            case SKPaymentTransactionStateFailed:
                // 购买失败
                [self handleFailedTransaction:transaction];
                break;
                
            case SKPaymentTransactionStateRestored:
                // 恢复购买
                [self handleRestoredTransaction:transaction];
                break;
                
            case SKPaymentTransactionStateDeferred:
                // 交易延迟（儿童限制等）
                NSLog(@"交易延迟...");
                break;
                
            default:
                break;
        }
    }
}

// 处理购买成功
- (void)handlePurchasedTransaction:(SKPaymentTransaction *)transaction {
    NSLog(@"购买成功: %@", transaction.payment.productIdentifier);
    
    // 获取凭证数据
    NSData *receiptData = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
    
    // 验证凭证
    if (receiptData) {
        [self verifyReceipt:receiptData isSandbox:NO completion:^(IAPStatus status, NSDictionary * _Nullable info, NSError * _Nullable error) {
            if (self.completion) {
                if (status == IAPStatusVerified) {
                    self.completion(IAPStatusSuccess, @{@"transaction": transaction, @"receipt": info}, nil);
                } else {
                    self.completion(IAPStatusUnverified, @{@"transaction": transaction}, error);
                }
            }
        }];
    } else {
        if (self.completion) {
            self.completion(IAPStatusSuccess, @{@"transaction": transaction}, nil);
        }
    }
    
    // 完成交易
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

// 处理购买失败
- (void)handleFailedTransaction:(SKPaymentTransaction *)transaction {
    NSLog(@"购买失败: %@", transaction.error.localizedDescription);
    
    if (self.completion) {
        self.completion(IAPStatusFailed, @{@"transaction": transaction}, transaction.error);
    }
    
    // 完成交易
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

// 处理恢复购买
- (void)handleRestoredTransaction:(SKPaymentTransaction *)transaction {
    NSLog(@"恢复购买: %@", transaction.payment.productIdentifier);
    
    if (self.completion) {
        self.completion(IAPStatusRestored, @{@"transaction": transaction}, nil);
    }
    
    // 完成交易
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

// 恢复购买完成
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue {
    NSLog(@"恢复购买完成，共恢复 %lu 笔交易", (unsigned long)queue.transactions.count);
}

// 恢复购买失败
- (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error {
    NSLog(@"恢复购买失败: %@", error.localizedDescription);
    
    if (self.completion) {
        self.completion(IAPStatusFailed, nil, error);
    }
}

#pragma mark - 内存管理

- (void)dealloc {
    // 移除交易观察者
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}






@end

NS_ASSUME_NONNULL_END
